package cn.gs.util;

import cn.gs.common.CommonMain;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * @author gs
 */
public class TokenLocker {

    public static class InnerTokenLocker {

        private int value;

        public InnerTokenLocker() {
            value = CommonMain.random.nextInt();
        }

        public boolean equals(InnerTokenLocker locker) {
            if (locker == null) {
                return false;
            } else {
                return locker.value == value;
            }
        }
    }
    private InnerTokenLocker locker;
    private long lastActive = System.currentTimeMillis();

    private InnerTokenLocker getInnerTokenLocker() {
        if (locker == null || (System.currentTimeMillis() > CommonMain.commonMain.getSetting().getTokenLockerActiveTime() + lastActive)) {
            locker = null;
        }
        return locker;
    }

    public InnerTokenLocker create() {
        synchronized (this) {
            if (getInnerTokenLocker() != null) {
                return null;
            }
            locker = new InnerTokenLocker();
            lastActive = System.currentTimeMillis();
            return locker;
        }
    }

    public boolean valid(InnerTokenLocker locker) {
        synchronized (this) {
            if (getInnerTokenLocker() == null || this.locker == null) {
                return locker == this.locker;
            } else {
                return locker.equals(this.locker);
            }
        }
    }

    public boolean register(InnerTokenLocker locker) {
        synchronized (this) {
            if (getInnerTokenLocker() != null) {
                return false;
            } else {
                this.locker = locker;
                lastActive = System.currentTimeMillis();
                return true;
            }
        }
    }

    public void release() {
        synchronized (this) {
            locker = null;
        }
    }
}
